<?php

/**
 * Renders the list of social networking websites.
 */
function padd_theme_widget_socialnet($position='A') {
	global $_PADD_SOCIALNET, $_PADD_SOCIALNET_B;
	$array = ($position == 'A') ? $_PADD_SOCIALNET : $_PADD_SOCIALNET_B;
?>
	<ul class="socialnet clear-fix">
	<?php foreach ($array as $k => $v) : ?>
		<?php
			$url = '';
			$v->username = Padd_Option::get('sn_username_' . $k);
			if ('facebook' == $k) {
				$fburl = Padd_Option::get('sn_username_facebook');
				if (!padd_theme_check_facebook_url($fburl) && !empty($fburl)) {
					$v->username = $fburl;
					$url = (string) $v;
				} else if (!empty($fburl)) {
					$url = $fburl;
				}
				$v->username = '';
			} else if ('rss' == $k) {
				if (empty($v->username)) {
					$url = get_bloginfo('rss2_url');
				} else {
					$url = (string) $v;
				}
			} else {
				$url = (string) $v;
			}
		?>
		<?php if (!empty($v->username) || $k == 'rss') : ?>
		<?php 
			$follow = (!empty($v->username)) ? $v->username : $url;
		?>
		<li class="<?php echo $k; ?>">
			<a href="<?php echo $url; ?>" class="icon-<?php echo $k; ?>" title="<?php echo $v->network; ?>">
				<?php 
					echo '<span class="count">' . number_format(padd_get_transient($k,$follow) ) . '</span> ';
					echo '<span class="label">' . $v->short_desc . '</span>'; 
				?>
			</a>
		</li>
		<?php endif; ?>
	<?php endforeach; ?>
	</ul>
<?php
}

/**
 * Renders the content of the page.
 */
function padd_theme_widget_page($pid) {
	wp_reset_query();
	query_posts('page_id=' . $pid);
	the_post();
	the_content();
}

/**
 * Renders the twitter widget.
 */
function padd_theme_widget_twitter() {
	global $_PADD_SOCIALNET;
	$_PADD_SOCIALNET['twitter']->username = (Padd_Option::get('sn_username_twitter'));
	$padd_sb_twitter = Padd_Option::get('sn_username_twitter');
	$twitter = new Padd_Twitter($padd_sb_twitter, 3, true);
	$twitter->show_tweets();
	if (false) :
	?>
	<p class="follow"><a href="'<?php echo $_PADD_SOCIALNET['twitter']; ?>'"><?php echo __('Follow us on Twitter', PADD_THEME_SLUG); ?></a></p>
	<?php
	endif;
}

/**
 * Renders the banner advertisement
 */
function padd_theme_widget_banner() {
	$ad = Padd_Option::get('ads_728090_1');
	echo stripslashes($ad);
}

/**
 * Renders the advertisements.
 */
function padd_theme_widget_sponsors() {
	echo '<div class="ads-area clear-fix">';
	$ad = Padd_Option::get('ads_300250_1');
	echo stripslashes($ad);
	echo '</div>';
}

function padd_theme_widget_ads_area() {
	echo '<div class="ads-area">';
	for ($i=1;$i<=4;$i++) {
		$ad = Padd_Option::get('ads_125125_' . $i,'');
		echo '<div class="ads-wrap ads-',  $i, '"><div class="ads">', stripslashes($ad), '</div></div>';
	}
	echo '<div class="clear"></div>';
	echo '</div>';
}

/**
 * Renders the Facebook Like Box.
 *
 * @paran string $id Facebook numerical ID
 * @param int $w Width of the box
 * @param int $h Height of the box
 * @param int $conn Number of connections
 * @param int $stream News feed streaming. 1 to enable, 0 to disable. The default value is 0.
 * @param int $header Like Box header. 1 to show, 0 to hide. The default value is 0.
 */
function padd_theme_widget_facebook_likebox($w=288,$h=340,$conn=10,$stream=0,$header=0) {
	global $_PADD_SOCIALNET;
	$fburl = Padd_Option::get('sn_username_facebook');
	if (!padd_theme_check_facebook_url($fburl)) {
		$_PADD_SOCIALNET['facebook']->username = $fburl;
		$fburl = (string) $_PADD_SOCIALNET['facebook'];
	}
?>
<iframe src="http://www.facebook.com/plugins/likebox.php?href=<?php echo urlencode($fburl); ?>&amp;width=<?php echo $w; ?>&amp;connections=<?php echo $conn; ?>&amp;stream=<?php echo $stream == 1 ? 'true' : 'false'; ?>&amp;header=<?php echo $header == 1 ? 'true' : 'false'; ?>&amp;height=<?php echo $h; ?>" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:<?php echo $w; ?>px; height:<?php echo $h; ?>px;"></iframe>
<?php
}

/**
 * Renders the Facebook Like Box.
 *
 * @paran string $id Facebook numerical ID
 * @param int $w Width of the box
 * @param int $h Height of the box
 * @param int $conn Number of connections
 * @param int $stream News feed streaming. 1 to enable, 0 to disable. The default value is 0.
 * @param int $header Like Box header. 1 to show, 0 to hide. The default value is 0.
 */
function padd_theme_widget_facebook_likebox_plus($w=278,$h=340,$conn=10,$stream=0,$header=0) {
	global $_PADD_SOCIALNET;
	$fburl = Padd_Option::get('sn_username_facebook');
	if (!padd_theme_check_facebook_url($fburl)) {
		$_PADD_SOCIALNET['facebook']->username = $fburl;
		$fburl = (string) $_PADD_SOCIALNET['facebook'];
	}
?>
<iframe src="http://www.facebook.com/plugins/likebox.php?href=<?php echo urlencode($fburl); ?>&amp;width=<?php echo $w; ?>&amp;connections=<?php echo $conn; ?>&amp;stream=<?php echo $stream == 1 ? 'true' : 'false'; ?>&amp;header=<?php echo $header == 1 ? 'true' : 'false'; ?>&amp;height=<?php echo $h; ?>" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:<?php echo $w; ?>px; height:<?php echo $h; ?>px;"></iframe>
<?php
	padd_theme_widget_socialnet();
}


/**
 * Render the popular posts.
 */
function padd_theme_widget_wpp() {
	if (function_exists('get_mostpopular')) :
		get_mostpopular('pages=0&stats_comments=1&range=all&limit=5&thumbnail_selection=usergenerated&thumbnail_width=77&thumbnail_height=67&do_pattern=1&pattern_form={title}{stats}');
	elseif (function_exists('wpp_get_mostpopular')) :
		wpp_get_mostpopular('pages=0&stats_comments=1&range=all&limit=5&thumbnail_selection=usergenerated&thumbnail_width=77&thumbnail_height=67&do_pattern=1&pattern_form={title}{stats}');
	else :
	?>
		<p>Please install the <a href="http://wordpress.org/extend/plugins/wordpress-popular-posts/">Wordpress Popular Posts plugin</a>.</p>
	<?php
	endif;
}

function padd_recent_comments($limit=5, $w=60) {
	$limit = !empty($limit) ? $limit : 5;
	$comments = get_comments('status=approve&number=' . $limit);
	if ($comments) {
		echo '<ul class="recent-comments">';
		foreach ($comments as $comment) :
			echo '<li>';
			echo get_avatar($comment, 70);
			echo '<div class="comm">';
			echo '<p class="meta"><a title="', esc_attr(get_the_title($comment->comment_post_ID)),'"href="', get_permalink($comment->comment_post_ID) ,'">', sprintf(__('%1$s on %2$s', PADD_THEME_SLUG), get_comment_author($comment->comment_ID), get_the_title($comment->comment_post_ID)), '</a></p>';
			echo '<p class="content">';
			comment_excerpt($comment->comment_ID);
			echo '</p>';
			echo '</div>';
			echo '</li>';
		endforeach;
		echo '</ul>';
	} else {
		echo '<p>', __('There are no comments in all entries.', THEMECREDIBLE_THEME_SLUG), '</p>';
	}
}


/**
 * Renders the recent posts, optionally with dates.
 *
 * @global WP_DB $wpdb
 * @global string $wp_locale
 * @param array|string $args
 * @return string
 */
function padd_theme_widget_recent_posts($args = '') {
	global $wpdb, $wp_locale;

	$defaults = array(
		'limit' => '3',
		'format' => 'html', 'before' => '',
		'after' => '', 'show_post_count' => false,
		'echo' => 1, 'show_date' => true, 'date_format' => 'F j, Y'
	);

	$r = wp_parse_args($args,$defaults);
	extract($r, EXTR_SKIP);

	if ('' == $type) {
		$type = 'monthly';
	}

	if ('' != $limit) {
		$limit = absint($limit);
		$limit = ' LIMIT ' . $limit;
	}

	$where = apply_filters('getarchives_where',"WHERE post_type = 'post' AND post_status = 'publish'",$r);
	$join = apply_filters('getarchives_join',"", $r);

	$output = '';

	$orderby = "post_date DESC ";
	$query = "SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit";
	$key = md5($query);
	$cache = wp_cache_get('padd_recent_posts','general');
	if (!isset($cache[ $key ])) {
		$arcresults = $wpdb->get_results($query);
		$cache[$key] = $arcresults;
		wp_cache_set('padd_recent_posts',$cache,'general');
	} else {
		$arcresults = $cache[$key];
	}
	if ($arcresults) {
		add_filter('excerpt_length', 'padd_theme_hook_excerpt_recent_posts_length');
		foreach ((array) $arcresults as $arcresult) {
			if ($arcresult->post_date != '0000-00-00 00:00:00' ) {
				$url = get_permalink($arcresult);
				$arc_title = $arcresult->post_title;
				if ($arc_title) {
					$text = strip_tags(apply_filters('the_title', $arc_title));
				} else {
					$text = $arcresult->ID;
				}
				$img = trim(get_the_post_thumbnail($arcresult->ID, PADD_THEME_SLUG . '-thumbnail-recent-posts'));
				$def = get_template_directory_uri() . '/images/thumbnail-recent-posts.png';
				if (empty($img)) {
					$img = '<img src="' . $def . '" title="Thumbnail" alt="Thumbnail" />';
				}
				$output .= '<li>';
				$output .= '<a href="' . get_permalink($arcresult->ID) . '" title="Permalink to ' . $text . '" class="thumbnail">' . $img . '</a>';
				$output .= '<a href="' . get_permalink($arcresult->ID) . '" title="Permalink to ' . $text . '" class="post-title">' . $text . '</a> ';
				$output .= '<span class="content">';
				$output .= get_the_excerpt();
				$output .= '</span>';
				$output .= '<span class="read-more"><a href="' . get_permalink($arcresult->ID) . '" title="Permalink to ' . $text . '" class="read-more">' . __('Read More', PADD_THEME_SLUG) . '</a></span>';
				$output .= '<div class="clear"></div>';
				$output .= '</li>';
			}
		}
		remove_filter('excerpt_length', 'padd_theme_hook_excerpt_recent_posts_length');
	}

	if ($echo) {
		echo $output;
	} else {
		return $output;
	}
}

/**
 * Renders the list of most discussed posts.
 *
 * @param string $range The time range for most discussed posts.
 * @param int $limit
 * @param array $post_types
 */
function padd_theme_most_discussed($range='alltime', $limit=5, $post_types=array('post')) {
	$args  = array(
	    'post_type' => $post_types,
	    'posts_per_page' => $limit,
	    'orderby' => 'comment_count',
	    'order' => 'DESC',
	    'ignore_sticky_posts' => 1
	);

	switch ($range) {
		default:
		case 'alltime':
			break;
		case 'daily':
			$today = getdate();
			$args['year'] = $today['year'];
			$args['monthnum'] = $today['mon'];
			$args['day'] = $today['mday'];
			break;
		case 'weekly':
			$args['year']= date('Y');
			$args['w'] = date('W');
			break;
		case 'monthly':
			$today = getdate();
			$args['year'] = $today['year'];
			$args['monthnum'] = $today['mon'];
			break;
		case 'yearly':
			$args['year']= date('Y');
			break;
	}

	$query = new WP_Query($args);

	if ($query->have_posts()) {
		$default_img = get_template_directory_uri() . '/styles/images/default-sidebar.png';
		echo '<ul class="with-thumbnail most-discussed">';
		while ($query->have_posts()) :
			$query->the_post();
			echo '<li>';
			echo '<span class="thumbnail">';
			echo '<a title="', sprintf(__('Permanent Link to %s', PADD_THEME_SLUG), the_title_attribute('echo=0')), '" href="', get_permalink(), '">';
			if (has_post_thumbnail(get_the_ID())) {
				echo get_the_post_thumbnail(get_the_ID(), Padd_Setup::get_image_name('sidebar'));
			} else {
				echo '<img src="' . $default_img . '" alt="Default Thumbnail" />';
			}
			echo '</a>';
			echo '</span>';
			echo '<p class="content">';
			echo '<span class="post-title"><a title="', sprintf(__('Permanent Link to %s', PADD_THEME_SLUG), the_title_attribute('echo=0')), '" href="', get_permalink(), '">', get_the_title(),'</a></span>';
			echo '<span class="byline-top">';
			echo get_the_time(__('F j, Y', PADD_THEME_SLUG));
			echo ' / </span>';
			echo '<span class="comment-count"><a href="' . get_comments_link() . '">';
			comments_number('No Comments', '1 Comment', '% Comments');
			echo '</a></span>';
			echo '</p>';
			echo '<span class="clear"></span>';
			echo '</li>';
		endwhile;
		echo '</ul>';
	} else {
		echo '<p>', __('There are no records to tabulate the most discussed entries.', PADD_THEME_SLUG), '</p>';
	}

	wp_reset_postdata();
}

/**
 * Renders the discussion tabs.
 *
 * @param array $p_1 Parameters for the most discussed posts.
 * @param array $p_2 Parameters for recent comments.
 */
function padd_theme_widget_discussion_tabs($p_1=null, $p_2=null) {
	$param_1 = array(
	    'range' => 'alltime',
	    'limit' => 5,
	    'post_types' => array('post')
	);
	$param_2 = array(
	    'limit' => 5,
	    'w' => 60
	);
	if (!is_null($p_1)) {
		$param_1 = array_merge($param_1, $p_1);
	}
	if (!is_null($p_2)) {
		$param_2 = array_merge($param_2, $p_2);
	}
	?>
<div class="discussion-tabs">
	<ul>
		<li><a href="#discuss-most"><?php echo __('Popular', PADD_THEME_SLUG); ?></a></li>
		<li><a href="#discuss-recent"><?php echo __('Comments', PADD_THEME_SLUG); ?></a></li>
		<li><a href="#discuss-tags"><?php echo __('Tags', PADD_THEME_SLUG); ?></a></li>
	</ul>
	<div class="panel" id="discuss-most">
		<h2 class="tab-title"><?php echo __('Popular Posts', PADD_THEME_SLUG); ?></h2>
		<?php padd_theme_most_discussed($param_1['range'], $param_1['limit'], $param_1['post_types']); ?>
	</div>
	<div class="panel" id="discuss-recent">
		<h2 class="tab-title"><?php echo __('Recent Comments', PADD_THEME_SLUG); ?></h2>
		<?php padd_recent_comments($param_2['limit'], $param_2['w']); ?>
	</div>
	<div class="panel" id="discuss-tags">
		<h2 class="tab-title"><?php echo __('Tag Cloud', PADD_THEME_SLUG); ?></h2>
		<?php wp_tag_cloud(); ?>
	</div>
	<div class="clear"></div>
</div>
	<?php
}

/*
 * Renders featured Flickr Photos.
 */
function padd_theme_widget_flickrrss_ru() {
?>
<div class="interior clear-fix">
<?php
	if (function_exists('get_flickrRSSRU')) {
		get_flickrRSSRU();
	} else {
		echo '<p>', sprintf(__('You have to install the <a href="%s">FlickrRSS RU</a> plugin first.', PADD_THEME_SLUG),'http://wordpress.org/extend/plugins/flickrrss-ru/') , '</p>';
	}
?>
</div>
<?php
}

/**
 * Retrieve transient value.
 *
 * Returns a transient value, or updates that transient if it has expired.
 *
 * @param $name String. Name of the service, e.g. twitter
 * @param $username String. Username for th service.
 * @return String. New transient value.
 */
function padd_get_transient($name = 'twitter', $username) {
	$transName = "padd-transient-$name"; // Name of value in database.
	$cacheTime = 8; // Time in hours between updates.
 
	// Do we already have saved tweet data? If not, lets get it.
	if(false === ($trans = get_transient($transName) ) ) :
 
		// Make the name of the function that gets our transient value.
		$func = "padd_get_$name";
		if(function_exists($func) ) {
			$trans = $func($username);
		} else {
			$trans = 'Function not found.';
		}
 
		// Did we get a positive number? If not, use the old value.
		if(!absint($trans) > 0)
			$trans = get_transient($transName . '-old');
 
		// Save our new transient, plus save it in the longer "backup" transient.
		set_transient($transName, $trans, 60 * 60 * $cacheTime);
		set_transient($transName.'-old', $trans, 3 * 60 * 60 * $cacheTime);
	endif;
 
	return $trans;
}

/**
 * Get Twitter follower count.
 *
 * @return Int. Twitter follower number.
 */
function padd_get_twitter($user='paddsolutions') {

	$json = wp_remote_get("http://api.twitter.com/1/users/show.json?screen_name=" . $user);
 
	if(is_wp_error($json))
		return false;
 
	$twitterData = json_decode($json['body'], true);
 
	return intval($twitterData['followers_count']);
}

/**
 * Get RSS subscriber count from FeedBurner.
 *
 * @return Int. RSS follower number.
 */
function padd_get_rss($user='paddsolutions') {
	$xml = wp_remote_get('http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=' . $user);
 
	if(is_wp_error($xml))
		return false;
 
	$sxe = new SimpleXMLElement($xml['body']);
 
	return intval($sxe->feed->entry['circulation']);
}
